package com.gyllr.futuresc;

import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.NotificationManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;

import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_10;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.drafts.Draft_75;
import org.java_websocket.drafts.Draft_76;
import org.java_websocket.exceptions.InvalidDataException;
import org.java_websocket.framing.Framedata;
import org.java_websocket.framing.FramedataImpl1;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;

import android.support.v7.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Message;
import android.text.TextUtils;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    // 要申请的权限
    private String[] permissions = {Manifest.permission.READ_PHONE_STATE};
    private AlertDialog dialog;
    private TextView txt_ViewTop = null;
    private ImageView imageViewBottom = null;
    private Button btn_Connect = null;
    private Button btn_Disconnect = null;
    private Button startService;
    private Button stopService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            // 检查该权限是否已经获取
            int i = ContextCompat.checkSelfPermission(this, permissions[0]);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (i != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                showDialogTipUserRequestPermission();
            } else {
                //已有权限直接启动Service
                Intent startIntent = new Intent(this,NotificationService.class);
                startService(startIntent);
            }
        } else {
            //低版本不需要申请权限,直接启动Service
            Intent startIntent = new Intent(this,NotificationService.class);
            startService(startIntent);
        }

        txt_ViewTop = (TextView) findViewById(R.id.txt_ViewTop);
        txt_ViewTop.setOnClickListener(this);
        imageViewBottom = (ImageView) findViewById(R.id.imageViewBottom);
        imageViewBottom.setOnClickListener(this);
        btn_Connect = (Button) findViewById(R.id.btn_Connect);
        btn_Connect.setOnClickListener(this);
        btn_Disconnect = (Button) findViewById(R.id.btn_Disconnect);
        btn_Disconnect.setOnClickListener(this);
        startService = (Button) findViewById(R.id.start_service);
        stopService = (Button) findViewById(R.id.stop_service);
        startService.setOnClickListener(this);
        stopService.setOnClickListener(this);
        startService.setClickable(false);

        txt_ViewTop.setText("已启动接收,关闭接收请点击下方\"关闭接收\"按钮");
        Log.v("debug", "onCreate调试信息");
    }

    @Override
    public void onClick(View v) {
        if(v==btn_Connect){
            Log.v("debug","发送通知");
        }else if(v==btn_Disconnect){
            Log.v("debug", "断开WS");
        }

        switch (v.getId()) {

            case R.id.start_service:
                Intent startIntent = new Intent(this,NotificationService.class);
                startService(startIntent);
                stopService.setClickable(true);
                v.setClickable(false);
                txt_ViewTop.setText("已启动接收,关闭接收请点击下方\"关闭接收\"按钮");
                break;

            case R.id.stop_service:
                Intent stopIntent = new Intent(this,NotificationService.class);
                stopService(stopIntent);
                startService.setClickable(true);
                v.setClickable(false);
                txt_ViewTop.setText("未启动接收,请点击下方的开始接收按钮");
                break;
            default:
                break;
        }

    }

    // 提示用户该请求权限的弹出框
    private void showDialogTipUserRequestPermission() {

        new AlertDialog.Builder(this)
                .setTitle("请开启\"获取手机信息\"或者\"电话\"权限")
                .setMessage("由于需要获取设备信息,请允许权限申请；\n否则，您将无法正常使用")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startRequestPermission();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .setCancelable(false)
                .show();
    }

    // 开始提交请求权限
    private void startRequestPermission() {
        ActivityCompat.requestPermissions(this, permissions, 321);
    }

    // 用户权限 申请 的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                    boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                    if (!b) {
                        // 用户还是想用我的 APP 的
                        // 提示用户去应用设置界面手动开启权限
                        showDialogTipUserGoToAppSettting();
                    } else
                        finish();
                } else {
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                    //已有权限直接启动Service
                    Intent startIntent = new Intent(this,NotificationService.class);
                    startService(startIntent);
                }
            }
        }
    }
    // 提示用户去应用设置界面手动开启权限

    private void showDialogTipUserGoToAppSettting() {

        dialog = new AlertDialog.Builder(this)
                .setTitle("没有\"获取手机信息\"或者\"电话\"权限")
                .setMessage("请在-应用设置-权限-中，允许本程序使用\"获取手机信息\"或者\"电话\"权限")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }

    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);

        startActivityForResult(intent, 123);
    }

    //
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 123) {

            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 检查该权限是否已经获取
                int i = ContextCompat.checkSelfPermission(this, permissions[0]);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 提示用户应该去应用设置界面手动开启权限
                    showDialogTipUserGoToAppSettting();
                } else {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                    //已有权限直接启动Service
                    Intent startIntent = new Intent(this,NotificationService.class);
                    startService(startIntent);
                }
            }
        }
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();

        Log.v("debug","onDestroy() executed");
    }
    @Override
    protected void onStart(){
        super.onStart();

        Log.v("debug","onStart() executed");
    }
    @Override
    protected void onStop(){
        super.onStop();

        Log.v("debug","onStop() executed");
    }
    @Override
    protected void onRestart(){
        super.onRestart();

        Log.v("debug","onRestart() executed");
    }
    @Override
    protected void onResume(){
        super.onResume();

        Log.v("debug","onResume() executed");
    }
    @Override
    protected void onPause(){
        super.onPause();

        Log.v("debug","onPause() executed");
    }
}
